package Rservetest.Rservetest;

import java.io.File;
import java.text.DecimalFormat;
import java.util.Properties;

import org.math.R.RserveSession;
import org.math.R.RserverConf;
import org.math.R.Rsession;
import org.math.R.Rsession.RException;

public class HaModelFit {
	public static void main(String args[]) throws RException {
		//远程R服务器应该有权限读取数据库!!!!并且安装好GDAL,proj4和GEOS开源GIS库，有权限安装R包
		//远程R服务器运行Rserve::Rserve(args=' --no-restore --no-save --slave --RS-enable-remote',quote=F)
		RserverConf rconf = new RserverConf("10.10.10.56", 6311, "", "", new Properties());		
		Rsession s = null;
		s = RserveSession.newRemoteInstance(System.out, rconf);
		s.setCRANRepository("https://mirrors.tuna.tsinghua.edu.cn/CRAN/"); //设置安装镜像
//		s.voidEval("devtools::install_git('https://git.oschina.net/seifer_08ms/gwr.avm.git')"); //安装package，（不必每次都安装，仅为测试）
		s.voidEval("library(gwr.avm)");   //加载package
//		s.voidEval("install.dependencies()"); //安装依赖
		//建立数据库连接	10.16.1.161的 连接	
//		s.voidEval("con<-dbconnect(user='wangcl',"+
//				"password='wangchenliang_CR_2017',"+
//				"host='10.11.10.34',dbname='cityre_beijing',port=3307)");
		// 10.10.10.56 上的连接
		s.voidEval("con<-dbconnect(user ='datatestuser',"+
	               "password ='cityhousedata_db_2017',"+
	               "dbname = 'cityre_beijing',"+
	               "host = '10.11.10.34',port = 3307 )");
		//		# 读取基础数据
		s.voidEval("tabln.vec<-loadData(con=con,month_offset = -2)");
		//      # 过滤城市外数据点（重要！！！！！！）
		s.voidEval("tabln.vec$ha_info.sp<-tabln.vec$ha_info.sp%>%remove.spatial.outlier(city_code='bj')");
		//	    # 建立poi相关信息
		s.voidEval("poi.data.list<-getpoi.ras(con=con,tabln.vec = tabln.vec)");
		//	    # 取出得到POI信息的小区信息
		s.voidEval("tabln.vec$ha_info.sp<-poi.data.list$ha_info.sp");
		//	    # 准备建模数据
		s.voidEval("data.sets.all<-avm.data.train(tabln.vec,proptype = '11')");
		//	    # 分割训练集和测试集
		s.voidEval("data.sets<-data.split(data =data.sets.all,train.rate = 0.75)");
		//	    # 建模, 模拟小区房价
		s.voidEval("avm.models<-avm.fit(data.train = data.sets$train,"
				+ "dependentY = 'saleprice',ntree = 500,nround = 1000)");
		//	    # 测试集预测
		s.voidEval("pred.test.data<-avm.pred(train.models=avm.models,"
				+ "newdata=data.sets$test,testing = T)");
		s.voidEval("sapply(pred.test.data$pred%>%head,exp)");
		s.voidEval("print(pred.test.data$rmse)"); // 注：实际是rmsle
		s.voidEval("print(pred.test.data$mae)");
		s.voidEval("pre<-sapply(pred.test.data$pred,exp)");
		s.voidEval("err<-sapply(X = pre[,-1]%>%"
				+ "data.frame,function(x){pre[,'y'] - x})");

		s.voidEval("rmse <- function(error)" + 
				"{sqrt(mean(error^2,na.rm=T))}");
		////////////计算标准化RMSE（逆log后）//////////////////////////////
		double[] pred =(double[])s.eval(
				"sapply(err%>%data.frame,rmse)/ (max(pre[,1],na.rm=T)-min(pre[,1],na.rm=T))");
		DecimalFormat df = new DecimalFormat("####0.00");
		for(double val:pred){
			System.out.print("Value: " + df.format(val) + "\t");			
		}
		System.out.println();
		s.voidEval("print(sapply(err%>%data.frame,rmse)/"
				+ "(max(pre[,1],na.rm=T)-min(pre[,1],na.rm=T))%>%round(2))");
		
		//		# 保存路径，默认为'./models.avm'
		s.voidEval("model.path<-model.store.path('/tmp/avm')");	    
		//	    # 保存相关数据
		s.voidEval("saveRDS(tabln.vec,file.path(model.path,"
				+ "paste('bj','2017-7','tabha.rds',sep='_'))) ");
		s.voidEval("saveRDS(poi.data.list,"
				+ "file.path(model.path,paste('bj','2017-7','poiha.rds',sep='_')))");
		//        # 模型保存
		s.voidEval("avm.model.store(city_code='bj',avm.models = avm.models,"
				+"avm.model.store.path='./save',"
				+ "yearmonth = '2017-7',proptype = '11',dependentY = 'rentprice')");
		s.close();
	}

}
